package edu.npu.GraphTransform;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class Graph2PartitionDriver {
	int num = 5;
	public static class Graph2PartitionMapper extends Mapper<LongWritable, Text, Text, Text> {
		final String SEPARATOR = "\t";
		@Override
		protected void map(LongWritable key, Text value, Context context)
				throws IOException, InterruptedException {
			String line = value.toString();
			String[] splits = line.split(SEPARATOR);
			context.write(new Text(splits[0]), 
					new Text(splits[1] + SEPARATOR + splits[2]));
		}
	}
	
	public static class Graph2PartitionPartitioner extends Partitioner<Text, Text> {
		@Override
		public int getPartition(Text key, Text value, int num) {
			return Integer.parseInt(key.toString());
		}
	}
	
	public static class Graph2PartitionReducer extends Reducer<Text, Text, Text, Text> {
		@Override
		protected void reduce(Text key, Iterable<Text> values, Context context)
				throws IOException, InterruptedException {
			for(Text value : values) 
				context.write(key, value);
		}
	}
	public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
		Configuration conf = new Configuration();
		Job job = new Job(conf, "graph2partition");
		job.setJarByClass(Graph2PartitionDriver.class);
		job.setMapperClass(Graph2PartitionDriver.Graph2PartitionMapper.class);
		job.setReducerClass(Graph2PartitionDriver.Graph2PartitionReducer.class);
		job.setPartitionerClass(Graph2PartitionDriver.Graph2PartitionPartitioner.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(Text.class);
		job.setNumReduceTasks(5);
		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));
		job.waitForCompletion(true);
	}
}
